package com.flyoil.petromp.ui.activity.activity_me;

import android.content.Intent;
import android.icu.text.Normalizer;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cnpc.fyutils.ToastUtils;
import com.flyoil.petromp.Constant.ConstantNetworkCode;
import com.flyoil.petromp.R;
import com.flyoil.petromp.adapter.adapter_me.ItemMessageAdapter;
import com.flyoil.petromp.apiservice.HttpModel;
import com.flyoil.petromp.apiservice.OnObserverRetrofitResetCallBack;
import com.flyoil.petromp.base.BaseActivity;
import com.flyoil.petromp.base.BaseEntity;
import com.flyoil.petromp.base.BaseRecyAdapter;
import com.flyoil.petromp.entity.entity_me.MyMessageEntity;
import com.flyoil.petromp.ui.activity.activity_matter.OrderMessageActivity;
import com.flyoil.petromp.ui.activity.activity_repertory.ProjectMessageActivity;
import com.flyoil.petromp.ui.activity.activity_repertory.ServiceMessageActivity;
import com.flyoil.petromp.ui.activity.activity_repertory.SupplierMessageActivity;
import com.flyoil.petromp.utils.Dialog.DialogHintUtil;
import com.flyoil.petromp.utils.OrderUtl.OrderListUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的消息界面
 */
public class MyMessageActivity extends BaseActivity {
    private ItemMessageAdapter adapter;
    private LinearLayout line_button;
    private TextView tv_selectall, tv_delete;
    private boolean selected = false;//是否选中了
    private boolean selectedFinish = false;//是否全部选中
    private boolean canSelect = false;//是否可以进行编辑


    @Override
    protected int getContentViewResId() {
        return R.layout.activity_my_message;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setTextTitleName("我的消息");
        setTextRightName("编辑");
        httpModel = new HttpModel();
        line_button = $(R.id.line_message_button_layout);
        tv_delete = $(R.id.tv_my_message_delete);
        tv_selectall = $(R.id.tv_my_message_all_select);
        recyclerView = $(R.id.listrecy_my_message);
        setRecyviewLayoutManager(null);
        adapter = new ItemMessageAdapter(mContext);
        recyclerView.setAdapter(adapter);
        setOnRefreshListener(true);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        setBackOnclickListner(mContext);
        tv_selectall.setOnClickListener(onClickListener);
        tv_delete.setOnClickListener(onClickListener);
        setTextRightOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setListItemStstus();

            }
        });
        adapter.setOnItemClickListener(onItemClickListener);
    }

    private BaseRecyAdapter.OnItemClickListener onItemClickListener = new BaseRecyAdapter.OnItemClickListener() {

        @Override
        public void Onclick(int position, Object data) {
            MyMessageEntity.DataBean.ListBean entity = (MyMessageEntity.DataBean.ListBean) data;
            if (canSelect) {
                entity.setSelected(!entity.isSelected());
                recyclerView.notifyDataSetChanged();
                setLineButtonLayoutStatus(getListDataSelectSize());
            } else {
                Intent intent = new Intent();
                switch (entity.getType()) {
                    case OrderListUtil.REPERTORY_SUPPLIER:
                        intent.setClass(mContext, SupplierMessageActivity.class);
                        break;
                    case OrderListUtil.REPERTORY_SERVICE:
                        intent.setClass(mContext, ServiceMessageActivity.class);
                        break;
                    case OrderListUtil.REPERTORY_PRODUCT:
                        intent.setClass(mContext, ProjectMessageActivity.class);
                        break;
                    default:
                        intent.setClass(mContext, OrderMessageActivity.class);
                        break;
                }
                intent.putExtra("order_type", entity.getType());
                intent.putExtra("id", entity.getReceiptId());
                startActivity(intent);
            }
            if (entity.isIsRead()==false) {
                getMessageDetail(entity.getId());
            }


        }
    };

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_my_message_delete://删除
                    if (selected) {
                        showDeleteDialog();
                    }
                    break;
                case R.id.tv_my_message_all_select://全选
                    selectedFinish = !selectedFinish;
                    setListItemSelectAllStstus(selectedFinish);
                    break;

            }
        }
    };

    /**
     * 显示删除消息的弹框
     */
    private void showDeleteDialog() {
        DialogHintUtil.show_hint_message_diolog(mContext);
        if (selectedFinish) {
            DialogHintUtil.set_dialog_content("确定删除全部消息吗？");
        } else {
            DialogHintUtil.set_dialog_content("确定删除消息吗？");
        }

        DialogHintUtil.set_confirm_onclicklistener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StringBuffer ids = new StringBuffer();
                for (int i = 0; i < adapter.getData().size(); i++) {
                    if (adapter.getData().get(i).isSelected()) {
                        ids.append("," + adapter.getData().get(i).getId());
                    }
                }
                deleteMessageList(ids);

            }
        });
    }

    /**
     * 根据全选状态修改列表item是否选中的状态
     */
    private void setListItemSelectAllStstus(boolean selectAll) {
        for (int i = 0; i < adapter.getData().size(); i++) {
            adapter.getData().get(i).setSelected(selectAll);
        }
        recyclerView.notifyDataSetChanged();
        if (selectAll) {
            tv_selectall.setText("取消全选");
        } else {
            tv_selectall.setText("全选");
        }
        setLineButtonLayoutStatus(getListDataSelectSize());
    }

    /**
     * 根据是否可以进行编辑来修改布局的状态
     */
    private void setListItemStstus() {
        canSelect = !canSelect;
        if (canSelect) {//可以进行编辑
            setTextRightName("取消");
            for (int i = 0; i < adapter.getData().size(); i++) {
                adapter.getData().get(i).setCanSelectck(true);
            }
            line_button.setVisibility(View.VISIBLE);
        } else {
            setTextRightName("编辑");
            for (int i = 0; i < adapter.getData().size(); i++) {
                adapter.getData().get(i).setCanSelectck(false);
                adapter.getData().get(i).setSelected(false);
            }
            selected = false;
            selectedFinish = false;
            setLineButtonLayoutStatus(0);//将底部布局状体进行重置
            line_button.setVisibility(View.GONE);
        }
        recyclerView.notifyDataSetChanged();
    }

    /**
     * 获取列表上数据选中的个数
     *
     * @return
     */
    private int getListDataSelectSize() {
        int selectSize = 0;
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (adapter.getData().get(i).isSelected()) {
                selectSize++;
            }
        }
        if (selectSize > 0) {
            selected = true;
        } else {
            selected = false;
        }
        return selectSize;
    }

    /**
     * 根据数据的状态设置底部按钮布局的状态
     */
    private void setLineButtonLayoutStatus(int size) {
        if (size == 0) {
            tv_delete.setText("删除");
            tv_delete.setTextColor(getResources().getColor(R.color.gray_ccc));
        } else {
            tv_delete.setText("删除(" + size + ")");
            tv_delete.setTextColor(getResources().getColor(R.color.home_color));
            if (size == adapter.getItemCount()) {
                tv_selectall.setText("取消全选");
                selectedFinish = true;
            } else {
                tv_selectall.setText("全选");
                selectedFinish = false;
            }
        }

    }


    @Override
    protected void initdatas() {
        super.initdatas();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNumber", pageNumber);
        map.put("pageSize", pageSize);
        httpModel.getMessageList(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                MyMessageEntity entity = null;
                if (model instanceof MyMessageEntity)
                    entity = (MyMessageEntity) model;
                if (entity != null && entity.getData().getList() != null && model.getCode() == ConstantNetworkCode.SuccedCode) {
                    if (isFirstLoadck) {
                        isFirstLoadck = false;
                        adapter.setDataList(entity.getData().getList());
                        recyclerView.notifyDataSetChanged();
                        if (entity.getData().getList().size() > 0) {
                            onDataSucceed();
                            pageNumber++;
                        } else {
                            onDataNull(null);
                        }
                    } else {
                        if (pageNumber == 1) {
                            adapter.setDataList(entity.getData().getList());
                            recyclerView.notifyDataSetChanged();
                            onRefreshDataSucceed();
                        } else {
                            adapter.addBottonDatas(entity.getData().getList());
                            recyclerView.notifyDataSetChanged();
                            if (entity.getData().getList().size() < pageSize) {
                                onLoadDataFinish();
                            } else {
                                onLoadDataSucceed();
                            }
                        }
                        pageNumber++;
                    }

                } else {
                    if (isFirstLoadck) {
                        onDataNull(null);
                    } else {
                        if (pageNumber == 1) {
                            onRefreshDataError();
                        } else {
                            onLoadDataError();
                        }
                    }

                }

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    /**
     * 删除消息列表
     *
     * @param ids
     */
    private void deleteMessageList(StringBuffer ids) {
        Map<String, Object> map = new HashMap<>();
        map.put("ids", ids);
        httpModel.deleteMessageList(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    setListItemStstus();
                    onRefreshData();
                }
                DialogHintUtil.dismiss_dialog();
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    /**
     * 获取消息详情接口，用来改变单据的状态
     *
     * @param id
     */
    private void getMessageDetail(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        httpModel.getMessageDetail(map, new OnObserverRetrofitResetCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity model) {
                super.onSuccess(model);
                if (model.getCode() == ConstantNetworkCode.SuccedCode) {
                    onRefreshData();
                }
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    @Override
    protected void onRefreshData() {
        super.onRefreshData();
        initdatas();
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        initdatas();
    }
}
